import React, { PureComponent } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Avatar, Icon, Menu, message, Spin, Tag, Tooltip, Modal } from 'antd';
import moment from 'moment';
import screenfull from 'screenfull';
import groupBy from 'lodash/groupBy';
import router from 'umi/router';
import HeaderDropdown from '../HeaderDropdown';
import SelectLang from '../SelectLang';
import Guide from '../ourslook/Guide';
import styles from './index.less';
import { hasPermission } from '../../utils/uiUtils';
import NoticeIcon from '../NoticeIcon';
import { getWebPath, requestPromise } from '@/utils/request';
import uiUtils from '@/utils/uiUtils';

export default class GlobalHeaderRight extends PureComponent {
  constructor(props) {
    super(props);
    this.state = { fullscreenIconType: 'fullscreen' };
    this.getMessage();
  }

  getMessage() {
    requestPromise(`${getWebPath()}sys/user/msg/getMessages`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        this.setState({
          noticeData: res.data.list,
          unReadNum: res.data.num,
        });
      }
    });
  }

  // eslint-disable-next-line consistent-return
  getNoticeData = notices => {
    if (notices === undefined || notices.length === 0) {
      return {};
    }
    const newNotices = notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.datetime) {
        newNotice.datetime = moment(notice.datetime).fromNow();
      }
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      if (newNotice.extra && newNotice.status) {
        const color = {
          todo: '',
          processing: 'blue',
          urgent: 'red',
          doing: 'gold',
        }[newNotice.status];
        newNotice.extra = (
          <Tag color={color} style={{ marginRight: 0 }}>
            {newNotice.extra}
          </Tag>
        );
      }
      return newNotice;
    });
    const result = groupBy(newNotices, 'type');
    return result;
  };

  getUnreadData = noticeData => {
    if (noticeData === undefined) {
      return {};
    }
    const unreadMsg = {};
    Object.entries(noticeData).forEach(([key, value]) => {
      if (!unreadMsg[key]) {
        unreadMsg[key] = 0;
      }
      if (Array.isArray(value)) {
        unreadMsg[key] = value.filter(item => !item.read).length;
      }
    });
    return unreadMsg;
  };

  changeReadState = clickedItem => {
    const { id, read, description } = clickedItem;
    this.setState({
      modalVisible: true,
      messageDetail: description,
    });
    if (read) {
      return;
    }
    // const { dispatch } = this.props;
    // dispatch({
    //   type: 'global/changeNoticeReadState',
    //   payload: id,
    // });
    requestPromise(`${getWebPath()}sys/user/msg/messageDetail`, {
      method: 'POST',
      body: { id: id },
    }).then(res => {
      if (res && res.code === 0) {
        // this.setState({
        // noticeData: res.data.list,
        // unReadNum: res.data.num,
        // });
        this.getMessage();
      }
    });
  };

  changeScreenfull = () => {
    if (!screenfull.enabled) {
      message.warning(
        `${formatMessage({ id: 'component.globalHeader.fullscreen.browser.notwork' })}}`
      );
    } else {
      screenfull.toggle();
      screenfull.on('change', () => {
        this.setState({
          fullscreenIconType: screenfull.isFullscreen ? 'fullscreen-exit' : 'fullscreen',
        });
      });
    }
  };

  fetchMoreNotices = tabProps => {
    const { list, name } = tabProps;
    const { dispatch, notices = [] } = this.props;
    const lastItemId = notices[notices.length - 1].id;
    dispatch({
      type: 'global/fetchMoreNotices',
      payload: {
        lastItemId,
        type: name,
        offset: list.length,
      },
    });
  };

  updateAllReadStatus = () => {
    requestPromise(`${getWebPath()}sys/user/msg/changeAllReadStatus`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        message.success('全部设置为已读状态完成！');
        this.getMessage();
      }
    });
  };

  handleOk = e => {
    this.setState({
      modalVisible: false,
    });
  };

  handleCancel = e => {
    this.setState({
      modalVisible: false,
    });
  };

  render() {
    const {
      currentUser,
      fetchingMoreNotices,
      fetchingNotices,
      loadedAllNotices,
      onNoticeVisibleChange,
      onMenuClick,
      onNoticeClear,
      skeletonCount,
      theme,
    } = this.props;
    //设置默认的图像, 下面测试数据，不用到的删掉
    currentUser.avatar = currentUser.avatar
      ? currentUser.avatar
      : 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
    currentUser.name = currentUser.username ? currentUser.username : 'Serati Ma';

    currentUser.geographic = {
      province: { label: '浙江省', key: '330000' },
      city: { label: '杭州市', key: '330100' },
    };
    currentUser.country = 'China';
    currentUser.address = '西湖区工专路 77 号';
    currentUser.phone = '0752-268888888';
    currentUser.group = '蚂蚁金服－某某某事业群－某某平台部－某某技术部－UE';
    currentUser.notifyCount = 12;
    currentUser.unreadCount = 11;
    currentUser.signature = '海纳百川，有容乃大';
    currentUser.email = 'antdesign@alipay.com';
    currentUser.tags = [{ key: '0', label: '很有想法的' }, { key: '1', label: '专注设计' }];

    const { fullscreenIconType } = this.state;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
        {/*<Menu.Item key="userCenter">*/}
        {/*  <Icon type="user" />*/}
        {/*  <FormattedMessage id="menu.account.center" defaultMessage="account center" />*/}
        {/*</Menu.Item>*/}
        {/*个人设置 菜单都放开，如果个人设置其他菜单不需要，可以进行加权限，这里全部 放开*/}
        <Menu.Item key="userinfo">
          <Icon type="setting" />
          <FormattedMessage id="menu.account.settings" defaultMessage="account settings" />
        </Menu.Item>
        {/*<Menu.Item key="triggerError">*/}
        {/*  <Icon type="close-circle" />*/}
        {/*  <FormattedMessage id="menu.account.trigger" defaultMessage="Trigger Error" />*/}
        {/*</Menu.Item>*/}
        <Menu.Item key="DruidSQL" hidden={!hasPermission('sql:list')}>
          <Icon type="warning" />
          <FormattedMessage id="menu.account.DruidSQL" defaultMessage="Druid SQL" />
        </Menu.Item>
        <Menu.Item key="updateLog" hidden={!hasPermission('sys:log:list')}>
          <Icon type="info-circle" />
          <FormattedMessage id="menu.account.updateLog" defaultMessage="update log" />
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />
          <FormattedMessage id="menu.account.logout" defaultMessage="logout" />
        </Menu.Item>
      </Menu>
    );
    const loadMoreProps = {
      skeletonCount,
      loadedAll: loadedAllNotices,
      loading: fetchingMoreNotices,
    };
    const noticeData = this.getNoticeData(this.state.noticeData);
    const unreadMsg = this.getUnreadData(noticeData);
    let className = styles.right;
    if (theme === 'dark') {
      className = `${styles.right}  ${styles.dark}`;
    }
    return (
      <div className={className}>
        {/*头部搜索*/}
        {/*<HeaderSearch*/}
        {/*className={`${styles.action} ${styles.search}`}*/}
        {/*placeholder={formatMessage({ id: 'component.globalHeader.search' })}*/}
        {/*dataSource={[*/}
        {/*formatMessage({ id: 'component.globalHeader.search.example1' }),*/}
        {/*formatMessage({ id: 'component.globalHeader.search.example2' }),*/}
        {/*formatMessage({ id: 'component.globalHeader.search.example3' }),*/}
        {/*]}*/}
        {/*onSearch={value => {*/}
        {/*console.log('input', value); // eslint-disable-line*/}
        {/*}}*/}
        {/*onPressEnter={value => {*/}
        {/*console.log('enter', value); // eslint-disable-line*/}
        {/*}}*/}
        {/*/>*/}
        {/*使用帮助*/}
        {/*<Tooltip title={formatMessage({ id: 'component.globalHeader.help' })}>*/}
        {/*<a*/}
        {/*target="_blank"*/}
        {/*href="https://pro.ant.design/docs/getting-started"*/}
        {/*rel="noopener noreferrer"*/}
        {/*className={styles.action}*/}
        {/*>*/}
        {/*<Icon type="question-circle-o" />*/}
        {/*</a>*/}
        {/*</Tooltip>*/}
        <Guide className={styles.action} iconType="robot" />
        <Tooltip title={formatMessage({ id: 'component.globalHeader.fullscreen' })}>
          <a
            target="_blank"
            rel="noopener noreferrer"
            onClick={this.changeScreenfull}
            className={styles.action}
            id="fullscreenId"
          >
            <Icon type={fullscreenIconType} />
          </a>
        </Tooltip>
        <Modal
          title="消息详情"
          visible={this.state.modalVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          {/*{this.state.messageDetail}*/}
          {/*dangerouslySetInnerHTML 将转义后的标签正常显示 */}
          <div dangerouslySetInnerHTML={{ __html: this.state.messageDetail }} />
        </Modal>
        <NoticeIcon
          className={styles.action}
          count={this.state.unReadNum === undefined ? 0 : this.state.unReadNum}
          onItemClick={(item, tabProps) => {
            console.log(item, tabProps); // eslint-disable-line
            this.changeReadState(item, tabProps);
          }}
          locale={{
            emptyText: formatMessage({ id: 'component.noticeIcon.empty' }),
            clear: formatMessage({
              id: 'component.noticeIcon.changeread',
              defaultMessage: '全部已读',
            }),
            more: formatMessage({ id: 'component.noticeIcon.more' }),
            // loadedAll: formatMessage({ id: 'component.noticeIcon.loaded' }),
            // loadMore: formatMessage({ id: 'component.noticeIcon.loading-more' }),
          }}
          onClear={this.updateAllReadStatus}
          onLoadMore={this.fetchMoreNotices}
          onPopupVisibleChange={onNoticeVisibleChange}
          loading={fetchingNotices}
          onViewMore={() => router.push('/sys/sysmessagecenter')}
          // clearClose
        >
          <NoticeIcon.Tab
            count={unreadMsg.notification}
            list={noticeData === undefined ? [] : noticeData.notification}
            title={formatMessage({ id: 'component.globalHeader.notification' })}
            name="notification"
            emptyText={formatMessage({ id: 'component.globalHeader.notification.empty' })}
            emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
            showViewMore
            //{...loadMoreProps}
          />
          {/*<NoticeIcon.Tab*/}
          {/*  count={unreadMsg.message}*/}
          {/*  list={noticeData.message}*/}
          {/*  title={formatMessage({ id: 'component.globalHeader.message' })}*/}
          {/*  name="message"*/}
          {/*  emptyText={formatMessage({ id: 'component.globalHeader.message.empty' })}*/}
          {/*  emptyImage="https://gw.alipayobjects.com/zos/rmsportal/sAuJeJzSKbUmHfBQRzmZ.svg"*/}
          {/*  {...loadMoreProps}*/}
          {/*/>*/}
          {/*<NoticeIcon.Tab*/}
          {/*  count={unreadMsg.event}*/}
          {/*  list={noticeData.event}*/}
          {/*  title={formatMessage({ id: 'component.globalHeader.event' })}*/}
          {/*  name="event"*/}
          {/*  emptyText={formatMessage({ id: 'component.globalHeader.event.empty' })}*/}
          {/*  emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"*/}
          {/*  {...loadMoreProps}*/}
          {/*/>*/}
        </NoticeIcon>
        {/*段大志修改  这里要看那个属性作为判断*/}
        {currentUser.name || currentUser.userId ? (
          <HeaderDropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`} id="userCenterId">
              <Avatar
                size="small"
                className={styles.avatar}
                src={
                  currentUser.headImg === undefined ||
                  currentUser.headImg === '' ||
                  currentUser.headImg === null
                    ? currentUser.avatar
                    : currentUser.headImg
                }
                alt="avatar"
              />
              <span className={styles.name}>{currentUser.name}</span>
            </span>
          </HeaderDropdown>
        ) : (
          <Spin size="small" style={{ marginLeft: 8, marginRight: 8 }} />
        )}
        {/*语言选择*/}
        <SelectLang className={styles.action} />
      </div>
    );
  }
}
